<template>
	<view class="sp-section sp-index">
		<!-- swiper -->
		<view class="sp-index__swiper">
			<view class="sp-index__swiper-header">
				<text>今日</text>
				<image src="../../static/images/index/icon-camera.png"></image>
			</view>
			<view class="sp-index__swiper-nums sp-index__swiper-record" @click="$u.route('/pages/index/data')">
				<view>
					<label>未拍摄场</label>
					<text>{{ recordParams.f_farm_count }}<text>个</text></text>
				</view>
				<view>
					<label>未拍栋舍</label>
					<text>{{ recordParams.f_building_count }}<text>个</text></text>
				</view>
				<view>
					<label>已拍栋舍</label>
					<text>{{ recordParams.t_building_count }}<text>个</text></text>
				</view>
				<view>
					<label>料槽空的</label>
					<text>{{ recordParams.f_feed_count }}<text>个</text></text>
				</view>
				<view>
					<label>料槽过满</label>
					<text>{{ recordParams.t_feed_count }}<text>个</text></text>
				</view>
			</view>
			<!-- <image src="../../static/images/oa/banner.jpg" mode="widthFix" /> -->
		</view>
		
		<!-- 入口 -->
		<view class="sp-index__link">
			<view class="sp-index__link-item" @click="$u.route('/pages/room/index?type=1')">
				<image src="../../static/images/index/icon-task.png" mode="widthFix" />
				<text>料槽巡检</text>
			</view>
			<view class="sp-index__link-item" @click="setDisinfectStatus">
				<image src="../../static/images/index/icon-record.png" mode="widthFix" />
				<text>物料消毒</text>
			</view>
			<view class="sp-index__link-item" @click="$u.route('/pages/room/hug?type=2')">
				<image src="../../static/images/index/icon-task.png" mode="widthFix" />
				<text>背膘评分</text>
			</view>
			<view class="sp-index__link-item sp-index__link-empty" @click="$u.toast('更多功能正在开发中')">
				<text>敬请期待</text>
			</view>
		</view>
		
		<!-- 异常 -->
		<!-- <view class="sp-index__error">
			<view class="sp-title">
				<u-cell class="sp-oa__boxes-name" title="场内预警" />
			</view>
			<view class="sp-index__error-item" @click="$u.route('/pages/index/room')">
				<view class="sp-index__error-pics">
					<u-icon name="info-circle-fill" size="36rpx" color="rgba(255, 0, 0, .6)" />
				</view>
				<view class="sp-index__error-info">
					物料烘干已结束超4小时
				</view>
				<view class="sp-index__error-addr">
					<u-tag text="第一养殖场" type="warning" plain plainFill></u-tag>
				</view>
			</view>
			<view class="sp-index__error-item" @click="$u.route('/pages/index/room')">
				<view class="sp-index__error-pics">
					<u-icon name="info-circle-fill" size="36rpx" color="rgba(255, 0, 0, .6)" />
				</view>
				<view class="sp-index__error-info">
					空的料槽有两个
				</view>
				<view class="sp-index__error-addr">
					<u-tag text="第一养殖场 - 1栋11栏" type="warning" plain plainFill></u-tag>
				</view>
			</view>
		</view> -->
		
		<!-- 数据 -->
		<!-- <view class="sp-title">
			<u-cell class="sp-oa__boxes-name" title="今日数据" />
		</view>
		<view class="sp-index__datas">
			<view class="sp-index__datas-item" @click="$u.route('/pages/index/data')">
				<text>未拍摄场</text>
				<text>1个</text>
			</view>
			<view class="sp-index__datas-item" @click="$u.route('/pages/index/data')">
				<text>未拍栋舍</text>
				<text>1个</text>
			</view>
			<view class="sp-index__datas-item" @click="$u.route('/pages/index/data')">
				<text>已拍栋舍</text>
				<text>1个</text>
			</view>
			<view class="sp-index__datas-item" @click="$u.route('/pages/index/data')">
				<text>料量不足</text>
				<text>1个</text>
			</view>
			<view class="sp-index__datas-item" @click="$u.route('/pages/index/data')">
				<text>执行操作</text>
				<text>1个</text>
			</view>
		</view> -->
		
		<!-- 拍照记录 -->
		<view class="sp-room__logs sp-index__history">
			<view class="sp-room__logs-title">
				<text>拍照记录</text>
				<view class="sp-room__logs-tabs">
					<text @click="getTabs(0)" :class="{ 'active': tabsIndex === 0 }">料槽</text>
					<text @click="getTabs(1)" :class="{ 'active': tabsIndex === 1 }">消毒</text>
					<text @click="getTabs(2)" :class="{ 'active': tabsIndex === 2 }">背膘</text>
				</view>
			</view>
			<view class="sp-filter">
				<view class="sp-filter__date" @click="dateStatus = true">
					<image src="../../static/images/index/icon-date.png"></image>
					<text class="sp-filter__date-desc">开始时间-结束时间</text>
					<!-- <text></text> -->
				</view>
				<view class="sp-filter__menu">
					<image src="../../static/images/index/icon-filter.png"></image>
				</view>
			</view>
			<!-- 料槽 -->
			<view class="sp-room__logs-list" v-if="tabsIndex == 0">
				<template v-if="history && history.length">
					<view class="sp-room__logs-item" v-for="(item, $index) in history" :key="item.id" @click="$u.route('/pages/index/room', { info: JSON.stringify(item) })">
						<view class="sp-room__logs-pics">
							<u-image :src="item.path" :lazy-load="true" width="100%" height="404rpx" :fade="true" duration="450"></u-image>
							<!-- <u-tag :bgColor="colorMap[item.ai_has_feed]" :text="item.ai_has_feed" /> -->
							<sp-tag :text="item.ai_has_feed" />
						</view>
						<view class="sp-room__logs-info">
							<view class="sp-room__logs-name">
								<text>栏位</text>
								<text>{{ item.column_name }}</text>
							</view>
							<view class="sp-room__logs-desc">
								<text>拍照时间</text>
								<text>{{ item.operation_time }}</text>
							</view>
						</view>
					</view>
				</template>
				<template v-else>
					<!-- <u-empty /> -->
					<view style="flex: 1;"><sp-empty /></view>
				</template>
			</view>
			<!-- 消毒 -->
			<view class="sp-room__logs-list" v-if="tabsIndex == 1">
				<template v-if="task && task.length">
					<view class="sp-room__logs-item" v-for="item in task" :key="item.id" @click="toTaskDetail(item)">
						<view class="sp-room__logs-pics">
							<u-image v-if="item.images && item.images.length" :src="file + item.images[0].image_path" :lazy-load="true" width="100%" height="404rpx" :fade="true" duration="450"></u-image>
							<u-image v-else src="" :lazy-load="true" width="100%" height="404rpx" :fade="true" duration="450"></u-image>
						</view>
						<view class="sp-room__logs-info">
							<view class="sp-room__logs-name">
								<text>标题</text>
								<text>{{ item.title }}</text>
							</view>
							<view class="sp-room__logs-desc">
								<text>状态</text>
								<text>{{ item.type === '消毒' ? '浸泡' : item.type }} - {{ item.stageText }}</text>
								<!-- <u-tag v-if="item.stageText == '已完成'" text="已完成" type="success" size="mini" />
								<u-tag v-if="item.stageText == '待取出'" text="待取出" type="primary" size="mini" />
								<u-tag v-if="item.stageText == '进行中'" text="进行中" type="warning" size="mini" /> -->
							</view>
						</view>
					</view>
				</template>
				<template v-else>
					<sp-empty />
				</template>
			</view>
			<!-- 背膘 -->
			<view class="sp-room__logs-list" v-if="tabsIndex == 2">
				<template v-if="rate && rate.length">
					<view class="sp-room__logs-item" v-for="(item, $index) in rate" :key="item.id" @click="$u.route('/pages/index/rate', { info: JSON.stringify(item) })">
						<view class="sp-room__logs-pics">
							<u-image :src="item.path" :lazy-load="true" width="100%" height="404rpx" :fade="true" duration="450"></u-image>
						</view>
						<view class="sp-room__logs-info">
							<view class="sp-room__logs-name">
								<text>栏位</text>
								<text>{{ item.column_name }}</text>
							</view>
							<view class="sp-room__logs-desc">
								<text>拍照时间</text>
								<text>{{ item.operation_time }}</text>
							</view>
						</view>
					</view>
				</template>
				<template v-else>
					<!-- <u-empty /> -->
					<view style="flex: 1;"><sp-empty /></view>
				</template>
			</view>
		</view>
		
		<view style="height: 140rpx;"></view>
		
		<!-- 日历 -->
		<!-- <u-calendar :show="dateShow" mode="multiple" @close="dateShow = false" @confirm="dateShow = false"></u-calendar> -->
		
		<!-- 选择消毒种类 -->
		<u-popup :show="disinfectStatus" mode="bottom" round="40" closeable @close="disinfectStatus = false">
			<view class="sp-index__type-title" @click="farmShow = true">{{ farmCurrentName }}</view>
			<view class="sp-index__type-list">
				<!-- $u.route('/pages/disinfect/dry', { id: farmCurrentId, name: farmCurrentName }) -->
				<view class="sp-index__type-item" @click="toCreateTask('dry', farmCurrentId, farmCurrentName)">
					<image src="../../static/images/index/icon-type1.png"></image>
					<text>物资烘干</text>
				</view>
				<!-- $u.route('/pages/disinfect/soak', { id: farmCurrentId, name: farmCurrentName }) -->
				<view class="sp-index__type-item" @click="toCreateTask('soak', farmCurrentId, farmCurrentName)">
					<image src="../../static/images/index/icon-type2.png"></image>
					<text>物资浸泡</text>
				</view>
			</view>
		</u-popup>
		
		<!-- 选择农场 -->
		<u-picker :show="farmShow" :columns="[farm]" keyName="farm_name" closeOnClickOverlay @close="farmShow = false" @confirm="getFarm" />
		
		<!-- 日历 -->
		<u-calendar :show="dateStatus" mode="range" :min-date="minDate" :max-date="maxDate" closeOnClickOverlay @close="dateStatus = false" @confirm="getDate"></u-calendar>
		
		<!-- 料槽-未拍照提示 -->
		<u-popup :show="recordStatus" mode="center" round="40" @close="recordStatus = false">
			<view class="sp-popup__records">
				<view class="sp-popup__records-pics">
					<image src="../../static/images/index/record-tips.png"></image>
				</view>
			</view>
		</u-popup>
		
		<!-- 浸泡消毒完成 -->
		
		<!-- 物资消毒完成 -->
	</view>
</template>

<script>
	import { SECRET } from '@/config/index.js'
	import { file, getRecordsById, getTask, getTaskParams, getHugRecordsById } from '@/api/task.js'
	import { setAuthByEid, getFarm, getRecordParams, getRecordFeedListAsAi, setAuth } from '@/api/alot.js'
	import dayjs from '../../utils/dayjs.min.js'
	import spTag from '@/components/sp-ui/sp-tag.vue'
	
	export default {
		name: 'spIndex',
		components: {
			spTag
		},
		data () {
			return {
				file,
				tabs: [
					{ name: '料槽', index: 0 },
					{ name: '消毒', index: 1 },
				],
				tabsIndex: 0,
				colorMap: {
				  '适量': '#79E984',
				  '偏多': '#FF9F58',
				  '偏少': '#91C1FF',
				  '过满': '#F86060',
				  '空槽': '#59D3D3',
				  '未知': '#C3C3C3',
				  'AI其他': '#fbd950'
				},
				// dateShow: false,
				// 最大/最小时间
				minDate: '',
				maxDate: '',
				// 查看任务/消毒的时间
				date: '',
				dateStatus: false,
				// 消毒状态
				disinfectStatus: false,
				// 拍照历史记录
				history: [],
				historyTotal: 0,
				historyQueryParams: {
					page: 1,
					page_size: 8
				},
				// 背膘列表
				rate: [],
				rateTotal: 0,
				rateQueryParams: {
					page: 1,
					page_size: 8
				},
				// 栋舍列表
				build: [],
				// 任务列表
				task: [],
				taskTotal: 0,
				taskQueryParams: {
					page: 1,
					page_size: 8,
				},
				// 农场列表
				farm: [],
				farmCurrentId: null,
				farmCurrentName: '请选择场',
				farmShow: false,
				// 料槽未拍照
				recordStatus: false,
				recordPhotoDate: '',
				recordPhotoInHours: false,
				// 汇总统计
				taskParams: {},
				recordParams: {},
				// nums
				buildNo: 0,
				buildYes: 0,
				buildKong: 0,
				buildMan: 0,
				buildControl: 0
			}
		},
		onLoad () {
			this.date = [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
			this.maxDate = dayjs().add(1, 'day').format('YYYY-MM-DD')
			this.minDate = dayjs().subtract(1, 'month').format('YYYY-MM-DD')
		},
		onShow () {
			const token = uni.getStorageSync('token')
			if (token) {
				const refresh = uni.getStorageSync('refresh')
				if (refresh) {
					this.reset()
					// this.getTaskParamsCurrentDay()
					this.getRecordParamsCurrentDay()
					this.getTaskList()
					this.getRecordsList()
					uni.removeStorageSync('refresh')
				}
			}
		},
		created () {},
		mounted () {
			const token = uni.getStorageSync('token')
			if (!token) {
				this.setUserAuth()
			} else {
				this.getFarmInfo()
				// this.getTaskParamsCurrentDay()
				this.getRecordParamsCurrentDay()
				this.getTaskList()
				this.getRecordsList()
			}
		},
		methods: {
			getTabs(e) {
				this.tabsIndex = e
				// this.tabsIndex == 1 ? this.getTaskList() : this.getRecordsList()
				if (this.tabsIndex == 1) {
					this.task = []
					this.taskQueryParams.page = 1
					this.getTaskList()
				} else if (this.tabsIndex == 2) {
					this.history = []
					this.historyQueryParams.page = 1
					this.getRateRecordsList()
				} else {
					this.rate = []
					this.rateQueryParams.page = 1
					this.getRecordsList()
				}
			},
			reset() {
				this.history = []
				this.task = []
				this.taskQueryParams.page = 1
				this.historyQueryParams.page = 1
			},
			// 选择时间
			getDate(e) {
				this.date = [e[0], e[e.length - 1]]
				this.dateStatus = false
				this.reset()
				// this.getTaskList()
				// this.tabsIndex == 1 ? this.getTaskList() : this.getRecordsList()
				if (this.tabsIndex == 1) {
					this.task = []
					this.taskQueryParams.page = 1
					this.getTaskList()
				} else if (this.tabsIndex == 2) {
					this.history = []
					this.historyQueryParams.page = 1
					this.getRateRecordsList()
				} else {
					this.rate = []
					this.rateQueryParams.page = 1
					this.getRecordsList()
				}
				// this.getRecordsList()
			},
			// 获取料槽当日统计
			getRecordParamsCurrentDay() {
				
				const users = uni.getStorageSync('aiUserInfo')
				uni.request({
					url: `${getRecordParams}?institute=${users.enterprise_id}&phone=${users.username}`,
					method: 'GET',
					success: (res) => {
						this.recordParams = res.data.data
					},
					fail: (err) => {
						this.recordParams = {
							f_farm_count: '--',
							t_building_count: '--',
							f_building_count: '--',
							f_feed_count: '--',
							t_feed_count: '--',
							adjust_feed_count: '--'
						}
					}
				})
			},
			// 获取消毒当日统计
			async getTaskParamsCurrentDay() {
				const data = await getTaskParams()
				this.taskParams = data
			},
			// 任务详情
			toTaskDetail(item) {
				uni.setStorage({
					key: 'taskDetail',
					data: item,
					success: () => {
						this.$u.route('/pages/disinfect/detail', { id: item.building_id, name: item.building_name, mid: item.id, stage: item.stage })
					}
				})
			},
			// 去创建消毒任务
			toCreateTask(type, id, name) {
				if (!id) {
					this.$u.toast('请先选择农场')
					return false
				}
				this.disinfectStatus = false
				this.$u.route(`/pages/disinfect/${type}`, { id, name })
			},
			// 获取当前栋舍id下的背膘拍照记录 
			async getRateRecordsList() {
				const params = {
					...this.rateQueryParams
				}
				if (this.date && this.date.length) {
					params.start_time = `${this.date[0]} 00:00:00`
					params.end_time = `${this.date[1]} 23:59:59`
				}
				const { records, count } = await getHugRecordsById(params)
				this.rate = this.rate.concat(records && records.length ? records.map(item => {
					item.path = item.image + '?x-oss-process=image/resize,m_fixed,w_174,h_231'
					item.operation_time = dayjs(item.operation_time).format('MM-DD hh:mm')
					return item
				}) : [])
				this.rateTotal = Math.ceil(count / this.rateQueryParams.page_size)
			},
			// 获取当前栋舍id下的拍照记录 getHugRecordsById
			async getRecordsList() {
				uni.showLoading()
				const params = {
					...this.historyQueryParams
				}
				if (this.date && this.date.length) {
					params.start_time = `${this.date[0]} 00:00:00`
					params.end_time = `${this.date[1]} 23:59:59`
				}
				console.log('params', params)
				const { records, count } = await getRecordsById(params)
				if (records && records.length) {
					const token = uni.getStorageSync('token')
					const users = uni.getStorageSync('aiUserInfo')
					console.log(`${getRecordFeedListAsAi}${users.enterprise_id}&page=1&page_size=20&search_docking_id__in=` + JSON.stringify(records.map(item => item.id)))
					uni.request({
						url: `${getRecordFeedListAsAi}${users.enterprise_id}&page=1&page_size=20&search_docking_id__in=` + JSON.stringify(records.map(item => item.id)),
						method: 'get',
						dataType: 'json',
						header: {
							authorization: token
						},
						success: (res) => {
							this.history = this.history.concat(records && records.length ? records.map(item => {
								item.path = item.image + '?x-oss-process=image/resize,m_fixed,w_174,h_231'
								item.ai_has_feed = res.data.data.find(kt => kt.docking_id == item.id)?.ai_has_feed ?? "未知"
								item.operation_time = dayjs(item.operation_time).format('MM-DD hh:mm')
								return item
							}) : [])
						},
						fail: () => {
							this.history = this.history.concat(records && records.length ? records.map(item => {
								item.path = item.image + '?x-oss-process=image/resize,m_fixed,w_174,h_231'
								item.operation_time = dayjs(item.operation_time).format('MM-DD hh:mm')
								return item
							}) : [])
						},
						complete: () => {
							uni.hideLoading()
						}
					})
				}
				console.log('count', count)
				this.historyTotal = Math.ceil(count / this.historyQueryParams.page_size)
			},
			// 获取任务列表
			async getTaskList() {
				const params = {
					...this.taskQueryParams
				}
				if (this.date && this.date.length) {					
					params.start_time = `${this.date[0]} 00:00:00`
					params.end_time = `${this.date[1]} 23:59:59`
				}
				const { records, count } = await getTask(params)
				this.task = this.task.concat(records.map(item => {
					const start = dayjs(item.stage_updated_at).add(item.type === '烘干' ? 240 : 60, 'minute')
					const end = dayjs(new Date())
					const diffTime = end - start > (item.type === '烘干' ? 240 : 60) * 60 * 1000
					if (item.type === '烘干') {
						item.stageText = item.stage == 3 ? '已完成' : item.stage == '2' ? '待取出' : diffTime ? '待取出' : '进行中'
					} else {
						item.stageText = item.stage == 4 ? '已完成' : item.stage == '2' ? '待取出' : diffTime ? '待取出' : '进行中'
					}
					return item
				}))
				this.taskTotal = Math.ceil(count / this.taskQueryParams.page_size)
			},
			// 消毒状态
			setDisinfectStatus() {
				this.disinfectStatus = !this.disinfectStatus
			},
			// 选中的农场
			getFarm(e) {
				this.farmCurrentId = e.value[0].id
				this.farmCurrentName = e.value[0].farm_name
				this.farmShow = false
			},
			setUserAuth() {
				const userInfo = uni.getStorageSync('aiUserInfo')
				console.log('userInfo', userInfo)
				uni.request({
					url: setAuthByEid + `${userInfo.enterprise_id}/`,
					method: 'GET',
					header: {
						service: true
					},
					dataType: 'json',
					success: (resp) => {
						if (resp.data.code !== 0) {
							this.$u.toast('企业未授权')
							return false
						}
						const { secret_id, secret_key } = resp.data.data
						const secret = {
							secret_id,
							secret_key
						}
						uni.request({
							url: setAuth,
							method: 'POST',
							data: secret,
							dataType: 'json',
							success: (res) => {
								if (res.data.code === 0) {
									uni.setStorageSync('infos', res.data.data)
									uni.setStorageSync('token', res.data.data.token)
									this.getFarmInfo()
								} else {
									this.$u.toast('授权失败')
								}
							},
							fail: () => {
								this.$u.toast('AIOT授权失败')
							}
						})
					}
				})
			},
			// 获取农场数据
			getFarmInfo() {
				const token = uni.getStorageSync('token')
				const users = uni.getStorageSync('aiUserInfo')
				uni.request({
					url: `${getFarm}?institute=${users.enterprise_id}&phone=${users.username}&search_farmtype__name=消毒`,
					method: 'get',
					dataType: 'json',
					header: {
						authorization: token
					},
					success: (res) => {
						const list = res.data.data
						if (list && list.length) {
							this.farm = list.filter((item) => item.level === 0)
							this.build = list.filter((item) => item.level === 1)
							uni.setStorageSync('build', this.build)
						}
					}
				})
			}
		},
		onReachBottom () {
			if (this.tabsIndex === 0) {
				console.log('this.historyTotal', this.historyTotal)
				if (this.historyQueryParams.page > this.historyTotal) {
					return false
				}
				this.historyQueryParams.page++
				this.getRecordsList()
			}
			if (this.tabsIndex === 1) {
				if (this.taskQueryParams.page > this.taskTotal) {
					return false
				}
				this.taskQueryParams.page++
				this.getTaskList()
			}
			if (this.tabsIndex === 2) {
				if (this.rateQueryParams.page > this.rateTotal) {
					return false
				}
				this.rateQueryParams.page++
				this.getRateRecordsList()
			}
		},
		onPullDownRefresh () {
			this.date = [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
			this.taskQueryParams.page = 1
			this.historyQueryParams.page = 1
			this.rateQueryParams.page = 1
			this.task = []
			this.history = []
			this.getTaskList()
			this.getRecordsList()
			this.getRateRecordsList()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 500)
		},
		onShareAppMessage () {}
	}
</script>

<style lang="less">
	page {
		background: #fff;
	}
</style>
